package com.tg.app.activity.device.settings;

import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.view.Window;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.core.util.Consumer;

import com.tange.base.toolkit.NetworkUtil;
import com.tange.core.data.structure.Resp;
import com.tange.core.device.facade.ConnectStatus;
import com.tange.core.device.facade.DeviceFacade;
import com.tange.core.device.facade.Status;
import com.tg.app.R;
import com.tg.app.TGDevice;
import com.tg.app.activity.base.DeviceSettingsBaseActivity;
import com.tg.app.bean.DeviceReboot;
import com.tg.app.bean.DeviceReboot_;
import com.tg.app.camera.AVIOCTRLDEFs;
import com.tg.app.camera.Camera;
import com.tg.app.util.ObjectBoxUtil;
import com.tg.appcommon.android.ResourcesUtil;
import com.tg.appcommon.android.TGApplicationBase;
import com.tg.appcommon.android.TGLog;
import com.tg.appcommon.android.TGToast;

import io.objectbox.Box;

public class RebootActivity extends DeviceSettingsBaseActivity{
    private static final String TAG = "RebootActivity";
    private LinearLayout rebootLayout;
    private DeviceFacade deviceFacade;
    private CountDownTimer timer;
    private final int totalTime = 90;
    private final int intervalTime = 1000;
    private boolean isDoConnect = false;
    private boolean isRebootSucceeded = false;
    private Box<DeviceReboot> box;
    private DeviceReboot reboot;
    private TextView progressBar;

    @Override
    protected void onSetupFailed() {

    }

    @Override
    public boolean shouldSetStatusBarColor() {
        return true;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);//remove title bar  即隐藏标题栏
        setContentView(R.layout.activity_reboot);
        hideActionBar();
        initView();
        box = ObjectBoxUtil.getDeviceReboot();
        deviceFacade = new DeviceFacade(getIntent().getStringExtra(Camera.EXT_UUID));
        if (!NetworkUtil.isNetworkConnected(TGApplicationBase.getApplication())){
            removeRebootProgress();
        }
        if (deviceFacade != null) {
            deviceFacade.observeConnectStatus(connectStatusConsumer);
            deviceFacade.connect();
            if (NetworkUtil.isNetworkConnected(TGApplicationBase.getApplication())){
                if (box != null) {
                    reboot = box.query().equal(DeviceReboot_.uuid, deviceFacade.getDeviceId()).build().findFirst();
                    if (reboot != null) {
                        long used = (System.currentTimeMillis() - reboot.createdAt) / 1000;
                        TGLog.d(TAG, "used:" + used + ", reboot.createdAt = " + reboot.createdAt + ", System.currentTimeMillis() = " + System.currentTimeMillis());
                        if (used < totalTime && !deviceFacade.connected() || (deviceFacade.connected() && used < 25)) {
                            int progress = (int) (totalTime - used);
                            TGLog.d(TAG, "progress:" + progress);
                            updateRebootDeviceUI(progress);
                        } else {
                            removeRebootProgress();
                        }
                    }
                }
            }else{
                removeRebootProgress();
            }
        }
    }

    @Override
    protected void initView() {
        modifyToolBar(R.string.device_reboot);
        rebootLayout = findViewById(R.id.rl_settings_share_user_tip);
        progressBar = findViewById(R.id.progress_bar);
        rebootLayout.setOnClickListener(v -> {
            if (!TGDevice.getInstance().isNetwork(deviceFacade)){
                TGToast.showToast(R.string.txt_network_anomaly);
                if (deviceFacade != null) {
                    deviceFacade.connect();
                }
                return;
            }
            isRebootSucceeded = false;
            if (deviceFacade != null) {
                if (deviceFacade.connected()) {
                    rebootDevice();
                } else {
                    deviceFacade.connect();
                }
            }
        });
        backClickEvent();
    }

    private void updateRebootDeviceUI(int startTime) {
        rebootLayout.setClickable(false);
        rebootLayout.setEnabled(false);
        findViewById(R.id.tv_desc).setVisibility(View.GONE);

        timer = new CountDownTimer(startTime * 1000L, intervalTime) {
            @Override
            public void onTick(long millisUntilFinished) {
                int process = (int) (millisUntilFinished / 1000);
                String text = String.format(ResourcesUtil.getString(R.string.device_reboot_progress), process);
                TGLog.i(TAG, "text = " + text);
                progressBar.setText(text);
                if (process <= 60 && process % 3 == 0) {
                    TGLog.i(TAG, "getPassword");
                    if (deviceFacade != null) {
                        if (deviceFacade.connected()) {
                            isDoConnect = true;
                            rebootDeviceSucceeded();
                        }else{
                            deviceFacade.connect();
                        }
                    }
                }
                updateRebootProgress();
            }

            @Override
            public void onFinish() {
                if (!isRebootSucceeded) {
                    rebootDeviceFailed();
                }
                removeRebootProgress();
            }
        }.start();

    }

    private void rebootDeviceFailed() {
        progressBar.setText(R.string.failed);
        progressBar.setTextColor(getResources().getColor(R.color.tg_process_failed_bar));
    }

    private void updateRebootProgress() {
        if (box != null) {
            if (reboot == null) {
                reboot = new DeviceReboot();
                reboot.uuid = deviceFacade.getDeviceId();
                reboot.createdAt = System.currentTimeMillis();
            }
            box.put(reboot);
        }
    }

    private void removeRebootProgress() {
        if (box != null) {
            DeviceReboot deviceReboot = box.query().equal(DeviceReboot_.uuid, deviceFacade.getDeviceId()).build().findFirst();
            if (deviceReboot != null) {
                if (box.remove(deviceReboot)) {
                }
            }
        }
    }

    private void rebootDevice() {
        deviceFacade.getInstruct().create(AVIOCTRLDEFs.IOTYPE_USEREX_IPCAM_DEV_REBOOT_REQ).data(new byte[1]).send(new Consumer<Resp<byte[]>>() {
            @Override
            public void accept(Resp<byte[]> resp) {
                TGLog.d(TAG, "rebootDevice resp:" + resp.getCode() + " " + resp.getSuccess());
            }
        });

        isDoConnect = false;
        updateRebootDeviceUI(totalTime);
        if (reboot != null) {
            reboot.createdAt = System.currentTimeMillis();
        }
    }



    private void rebootDeviceSucceeded() {
        isRebootSucceeded = true;
        progressBar.setText(R.string.reboot_success);
        progressBar.setTextColor(getResources().getColor(R.color.tg_process_success_bar));
        if (timer != null) {
            timer.cancel();
        }
        if (box != null) {
            if (reboot == null) {
                reboot = new DeviceReboot();
                reboot.uuid = deviceFacade.getDeviceId();
            }
            reboot.createdAt = 0;
            box.put(reboot);
        }
        removeRebootProgress();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (timer != null) {
            timer.cancel();
        }
        reboot = null;
        box = null;
        deviceFacade.unObserveConnectStatus(connectStatusConsumer);
    }

    private final Consumer<ConnectStatus> connectStatusConsumer = connectStatus -> {
        if (connectStatus.getStatus() == Status.SUCCESS){
            TGLog.d(TAG,"连接成功");
        }else if (connectStatus.getStatus() == Status.FAILED){
            TGLog.d(TAG,"连接失败");
            isDoConnect = false;
        }else if (connectStatus.getStatus() == Status.DISCONNECTED_BY_DEVICE){
            deviceFacade.connect();
        }
    };
}